package cn.sirun.com.fca.account.view.impl;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.tencent.cloud.iov.common.flow.view.impl.BaseLoadingFlowView;
import com.tencent.cloud.iov.flow.view.IContentViewContainer;
import com.tencent.cloud.iov.kernel.constant.StatusCode;
import com.tencent.cloud.iov.kernel.model.BaseResponse;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ActivityUtils;
import com.tencent.cloud.iov.util.PatternMatchingUtils;
import com.tencent.cloud.iov.util.ResourcesUtils;
import com.tencent.cloud.iov.util.SRPUtils;
import com.tencent.cloud.iov.util.crypt.CustomSRPClient;
import com.tencent.cloud.iov.util.storage.TXCacheManager;
import com.tencent.cloud.uikit.utils.DialogUtils;
import com.tencent.cloud.uikit.utils.SystemUiUtils;
import com.tencent.cloud.uikit.widget.edittext.LineEditText;
import com.tencent.cloud.uikit.widget.edittext.PasswordEditText;

import cn.sirun.com.fca.account.R;
import cn.sirun.com.fca.account.constant.AccountActivityConst;
import cn.sirun.com.fca.account.constant.AccountIntentConst;
import cn.sirun.com.fca.account.constant.AccountStatusCode;
import cn.sirun.com.fca.account.model.login.AuthenticateRequest;
import cn.sirun.com.fca.account.model.login.AuthenticateResponse;
import cn.sirun.com.fca.account.model.login.ChallengeResponse;
import cn.sirun.com.fca.account.presenter.IConfirmPasswordPresenter;
import cn.sirun.com.fca.account.presenter.impl.ConfirmPasswordPresenter;
import cn.sirun.com.fca.account.uitl.AccountStatusUtils;
import cn.sirun.com.fca.account.uitl.IntentUtils;
import cn.sirun.com.fca.account.view.IConfirmPasswordView;

public class ConfirmPasswordFlowView extends BaseLoadingFlowView<IConfirmPasswordPresenter> implements
        IConfirmPasswordView {

    private TextView mPromptTV, mNextTV, mForgetPassTV;
    private View mLineView;
    private ImageView mPromptIV;
    private LineEditText mPasswordET;

    private int mFrom = AccountIntentConst.UNKNOWN;
    private String mPassword;
    private CustomSRPClient mCustomSRPClient;

    public ConfirmPasswordFlowView(Activity activity) {
        super(activity);
        mFrom = IntentUtils.getIntentFrom(getActivity().getIntent(), AccountIntentConst.UNKNOWN);
        mCustomSRPClient = SRPUtils.getCustomSRPClient();
    }

    public ConfirmPasswordFlowView(Activity activity, IContentViewContainer container) {
        super(activity, container);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        setUpActionBar();
        initView();
    }

    private void setUpActionBar() {
        final Activity activity = getActivity();
        SystemUiUtils.showActionBar(activity, "");
    }

    @Override
    public void onChallengeResult(BaseResponse<ChallengeResponse> response) {
        int code = response.getCode();
        if (StatusCode.SUCCESS == code) {
            ChallengeResponse challengeResponse = response.getData();
            String salt = challengeResponse.getSalt();
            String group = challengeResponse.getGroup();
            String publicKey = challengeResponse.getPublicKey();
            String[] authenticateInfo = SRPUtils.generateAuthenticateInfo(mCustomSRPClient,
                    mPassword, salt, group, publicKey);
            if (null == authenticateInfo) {
                hideLoadingView();
                DialogUtils.showToast(getActivity(), R.string.common_request_failed);
                return;
            }
//            TXCacheManager.getInstance().put(SRPUtils.SRP_SALT, challengeResponse.getSalt());
//            TXCacheManager.getInstance().put(SRPUtils.SRP_GROUP, challengeResponse.getGroup());
//            TXCacheManager.getInstance().put(SRPUtils.SRP_SERVER_PUBLIC_KEY,
//                    challengeResponse.getPublicKey());
            if (mFrom == AccountIntentConst.MODIFY_REGISTER_ACCOUNT
                    || mFrom == AccountIntentConst.MOIDFY_BIND_ACCOUNT) {
                getPresenter().changeAuthenticate(new AuthenticateRequest(authenticateInfo[0],
                        authenticateInfo[1]));
            } else {
                getPresenter().authenticate(new AuthenticateRequest(authenticateInfo[0],
                        authenticateInfo[1]));
            }
        } else {
            hideLoadingView();
            AccountStatusUtils.showToast(getActivity(), code);
        }
    }

    @Override
    public void onAuthenticateResult(BaseResponse<AuthenticateResponse> response) {
        hideLoadingView();
        int code = response.getCode();
        if (StatusCode.SUCCESS == code) {
            String serverEvidenceMessage = response.getData().getEvidenceMessage();
            if (!SRPUtils.verifyEvidenceMessage(mCustomSRPClient, serverEvidenceMessage)) {
                DialogUtils.showToast(getActivity(), R.string.common_request_failed);
                return;
            }
            if (mFrom == AccountIntentConst.MODIFY_REGISTER_ACCOUNT
                    || mFrom == AccountIntentConst.MOIDFY_BIND_ACCOUNT) {
                Intent intent = Router.fromPath(AccountActivityConst.Path.SETTING_REGISTER_ACCOUNT);
                intent.putExtra(AccountIntentConst.FROM, mFrom);
                ActivityUtils.startActivityForResult(getActivity(), intent);
            } else {
                Intent intent = Router.fromPath(AccountActivityConst.Path.MODIFY_PASS);
                ActivityUtils.startActivityForResult(getActivity(), intent);
            }
        } else {
            AccountStatusUtils.showToast(getActivity(), code);
        }
    }

    @Override
    protected IConfirmPasswordPresenter createPresenter() {
        return new ConfirmPasswordPresenter();
    }

    private void initView() {
        setContentView(R.layout.confirm_password_activity);
        final Activity activity = getActivity();
        mPromptTV = activity.findViewById(R.id.tv_pass_prompt);
        mNextTV = activity.findViewById(R.id.tv_next);
        mLineView = activity.findViewById(R.id.v_pass_line);
        mPromptIV = activity.findViewById(R.id.iv_pass_prompt);
        mPasswordET = activity.findViewById(R.id.et_pass);
        mForgetPassTV = activity.findViewById(R.id.tv_forget_pass);

        mPasswordET.setTextChangeListener(new LineEditText.OnTextChangeListener() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setConfirmBtnEnable();
            }
        });

        mNextTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (checkFormat()) {
                    showLoadingView();
                    if (mFrom == AccountIntentConst.MODIFY_REGISTER_ACCOUNT ||
                            mFrom == AccountIntentConst.MOIDFY_BIND_ACCOUNT) {
                        getPresenter().changeGetChallenge();
//                        Intent intent = Router.fromPath(AccountActivityConst.Path.SETTING_REGISTER_ACCOUNT);
//                        ActivityUtils.startActivityForResult(getActivity(), intent);
                    } else {
//                        Intent intent = Router.fromPath(AccountActivityConst.Path.MODIFY_PASS);
//                        ActivityUtils.startActivityForResult(getActivity(), intent);
                        getPresenter().challenge();
                    }
                }
            }
        });

        mForgetPassTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String path = AccountActivityConst.Path.PHONE;
                Intent intent = Router.fromPath(path);
                intent.putExtra(AccountIntentConst.FROM, AccountIntentConst.FORGET_PASSWORD);
                getActivity().startActivity(intent);
            }
        });

        initData();
    }

    private void initData() {
        if (mFrom == AccountIntentConst.MOIDFY_BIND_ACCOUNT
                || mFrom == AccountIntentConst.MODIFY_REGISTER_ACCOUNT) {
            mPromptTV.setText(R.string.login_password);
        } else {
            mPromptTV.setText(R.string.login_password2);
        }
    }

    private boolean checkFormat() {
        mPassword = mPasswordET.getText().toString();
        boolean isPasswordCorrect = PatternMatchingUtils.isPasswordCorrect(mPassword);
        if (isPasswordCorrect) {
            return true;
        } else {
            setNumberBg(R.string.login_password_error, R.color.login_register_text_color,
                    R.color.login_register_text_color, View.VISIBLE);
            return false;
        }
    }

    private void setConfirmBtnEnable() {
        String password = mPasswordET.getText().toString();
        int passwordLength = mPasswordET.length();
        boolean isPassCorrect = PatternMatchingUtils.isPasswordCorrect(password);
        if (0 == passwordLength || isPassCorrect) {
            if (mFrom == AccountIntentConst.MOIDFY_BIND_ACCOUNT
                    || mFrom == AccountIntentConst.MODIFY_REGISTER_ACCOUNT) {
                setNumberBg(R.string.login_password, R.color.grey_A9,
                        R.color.grey_DD, View.GONE);
            } else {
                setNumberBg(R.string.login_password2, R.color.grey_A9,
                        R.color.grey_DD, View.GONE);
            }
        }

        boolean isEnable = passwordLength >= PasswordEditText.MIN_LENGTH;

        if (isEnable) {
            mNextTV.setBackgroundResource(R.drawable.s_btn_bg_border);
        } else {
            mNextTV.setBackgroundResource(R.drawable.s_btn_default_bg_border);
        }
        mNextTV.setEnabled(isEnable);
    }

    private void setNumberBg(int text, int textColor, int LineColor, int visibility) {
        mPromptTV.setText(ResourcesUtils.getString(text));
        mPromptTV.setTextColor(ResourcesUtils.getColor(textColor));
        mLineView.setBackgroundColor(ResourcesUtils.getColor(LineColor));
        mPromptIV.setVisibility(visibility);
    }

}
